import 'package:flutter/material.dart';
import 'package:photo_kit/debug_tool.dart';
import 'package:photo_kit/photo_asset.dart';
import 'package:photo_kit/photo_texture_controller.dart';
import 'package:photo_kit/photo_texture_widget.dart';
import 'package:photo_kit/photo_kit.dart';
import 'package:photo_kit_example/album_photo_page.dart';

class AlbumTexturePhotoPage extends StatefulWidget {
  AlbumTexturePhotoPage({Key key}) : super(key: key);

  @override
  _AlbumTexturePhotoPageState createState() => _AlbumTexturePhotoPageState();
}

class _AlbumTexturePhotoPageState extends State<AlbumTexturePhotoPage> {
  // 在本类管理 controller 的生命周期
  List<PhotoTextureController> controllers = [];
  String title = 'Photo Texture';

  @override
  void initState() {
    super.initState();

    _reqeustPhotos();
    dprint('页面创建');
  }

  @override
  void dispose() {
    dprint('页面销毁');
    controllers.forEach((controller) {
      controller.dispose();
    });
    super.dispose();
  }

  Future _reqeustPhotos() async {
    List<PhotoAsset> photos = await PhotoKit.getAllPhoto();
    // photos = [photos[0]];
    for (PhotoAsset asset in photos) {
      final controller = PhotoTextureController(asset);
      // await controller.initialize();

      controllers.add(controller);
    }

    title = 'All Photo Texture ${photos.length}';
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return AlbumPhotoPage(
      title: title,
      itemCount: controllers.length,
      // countPerRow: 1,
      itemBuilder: (context, index) {
        dprint('构建控件 $index');

        final controller = controllers[index];

        return _ItemWidget(
          controller: controller,
          index: index,
        );
      },
    );
  }
}

class _ItemWidget extends StatelessWidget {
  const _ItemWidget({
    Key key,
    @required this.controller,
    this.index,
  }) : super(key: key);

  final PhotoTextureController controller;
  final int index;

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        border: Border.all(
          color: Colors.black,
          width: 1,
        ),
        color: Colors.black12,
      ),
      child: PhotoTextureWidget(
        controller,
        debugLabel: () => '$index, ${controller.textureId}',
      ),
    );
  }
}
